import { Breadcrumb, Table, Space, Button, TableProps, Modal, Cascader } from 'antd';
import React, { FC } from 'react';
import {
  FormPanel,
  type FormPanelObject,
  FormPanelStatus,
  FormPanelBtnDisplay,
  FormPanelBtnAlign,
  InputType,
} from 'lfun-bg-comp';
import _ from 'lodash';
import dayjs from 'dayjs';
import { PageContainer } from '@/component/page-container';
import { PAGINATIONCONFIG } from '@/constant/page';
import utils from '@/utils';
import { GENDER } from '@/constant/basicOptions';
import { InnerTransactionSearchParams, pageTransaction } from '@/service/student/instudent';
import { searchSchool } from '@/service/unit/school';
import { getGradeClassOptions } from '@/service/options';
import { STUDENT_APPROVALATATUS, STU_CHANGE_TYPE } from '@/constant/studentOptions';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';
import useCountry from '@/hooks/useCountry';

const Groups: FC = () => {
  //const navigate = useNavigate();
  const [value, setValue] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(10);
  const [pageIndex, setPageIndex] = React.useState(1);
  const [loading, setLoading] = React.useState(false);
  //const [condition, setCondition] = React.useState<any>({ audit_status: 'needaudit' });
  const [cur, setCur] = React.useState<any>();
  //const [curForm, setCurForm] = React.useState<any>();
  const [curFormPanelObject, setCurFormPanelObject] = React.useState<any>();
  const [visible, setVisible] = React.useState(false);
  const country = useCountry();

  const searchFunc = async (params, pageIndex, pageSize) => {
    setLoading(true);
    const param: InnerTransactionSearchParams = {
      ...params,
    };
    if (params.class_id && params.class_id.length > 1) {
      param.class_id = params.class_id[1];
    }
    const r = await pageTransaction(param, pageIndex, pageSize);
    if (r.success) {
      setValue(r.data.items);
      setTotal(r.data.total);
      setPageIndex(pageIndex);
      setPageSize(pageSize);
    } else if (curFormPanelObject) {
      curFormPanelObject.reVaildation(r);
    }
    setLoading(false);
  };
  const list = [
    {
      title: '',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '区县',
          name: 'borough',
          key: 'borough',
          inputType: InputType.select,
          relationFields: ['school_id'],
          renderOption: country,
        },
        {
          label: '学校名称',
          name: 'school_id',
          key: 'school_id',
          inputType: InputType.select,
          relationFields: ['class_id'],
          renderOption: async (form, values) => {
            let list = [];
            if (form.getFieldValue('borough')) {
              const r = await searchSchool({ borough: form.getFieldValue('borough') }, 1, 1000);
              if (r.success) {
                list = r?.data?.items?.map(item => ({
                  label: item.school_name,
                  value: item.id,
                  key: item.id,
                }));
              }
            }
            return list;
          },
        },
        {
          label: '性别',
          name: 'student_gender',
          key: 'student_gender',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '学籍号码',
          name: 'edu_number',
          key: 'edu_number',
          textRange: [0, 20],
        },
        {
          label: '班级',
          name: 'class_id',
          key: 'class_id',
          inputType: InputType.children,
          children: <Cascader />,
          renderOption: async (form: FormPanelObject) => {
            const list = await getGradeClassOptions(form);
            return list;
          },
        },
      ],
    },
  ];
  const showlist = [
    {
      title: '',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '姓名',
          name: 'student_name',
          key: 'student_name',
        },
        {
          label: '学籍号码',
          name: 'edu_number',
          key: 'edu_number',
        },
        {
          label: '性别',
          name: 'student_gender',
          key: 'student_gender',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '班级',
          name: 'class_name',
          key: 'class_name',
        },
        {
          label: '状态',
          name: 'approval_status',
          key: 'approval_status',
          inputType: InputType.select,
          renderOption: STUDENT_APPROVALATATUS,
        },
        {
          label: '异动类型',
          name: 'transaction_type',
          key: 'transaction_type',
          // inputType: InputType.children,
          // children: <Cascader />,
          // renderOption: STU_CHANGE_TYPE,
        },
        {
          label: '异动原因',
          name: 'transaction_reason',
          key: 'transaction_reason',
          // inputType: InputType.children,
          // children: <Cascader />,
          // renderOption: STU_CHANGE_TYPE,
        },
        {
          label: '行政属地',
          name: 'borough',
          key: 'borough',
          inputType: InputType.select,
          renderOption: country,
        },
        {
          label: '学校',
          name: 'school_name',
          key: 'school_name',
          width: 150,
        },
        {
          label: '提交时间',
          name: 'transaction_time',
          key: 'transaction_time',
          inputType: 'date',
        },
      ],
    },
  ];
  const columns: TableProps['columns'] = [
    {
      title: '姓名',
      dataIndex: 'student_name',
      key: 'student_name',
      width: 150,
      fixed: 'left',
    },
    {
      title: '学籍号码',
      dataIndex: 'edu_number',
      key: 'edu_number',
      width: 150,
    },
    {
      title: '性别',
      dataIndex: 'student_gender',
      key: 'student_gender',
      width: 80,
      render: (text: any) => {
        return _.find(GENDER, { value: String(text) })?.label;
      },
    },
    {
      title: '班级',
      dataIndex: 'class_name',
      key: 'class_name',
      width: 100,
      render: (text, record) => {
        return text ? `${text}班` : '';
      },
    },
    {
      title: '状态',
      dataIndex: 'approval_status',
      key: 'approval_status',
      width: 100,
      render: (text: any) => {
        return _.find(STUDENT_APPROVALATATUS, { value: String(text) })?.label;
      },
    },
    {
      title: '异动类型',
      dataIndex: 'transaction_type',
      key: 'transaction_type',
      width: 150,
      render: (text: any) => {
        if (!text) return '';
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(STU_CHANGE_TYPE, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '异动原因',
      dataIndex: 'transaction_reason',
      key: 'transaction_reason',
      width: 150,
    },
    {
      title: '行政属地',
      dataIndex: 'borough',
      key: 'borough',
      width: 150,
      render: (text: any) => {
        return _.find(country, { value: String(text) })?.label;
      },
    },
    {
      title: '学校',
      dataIndex: 'school_name',
      key: 'school_name',
      width: 150,
    },
    {
      title: '提交时间',
      dataIndex: 'transaction_time',
      key: 'transaction_time',
      width: 150,
      render: (text, record) => {
        return record.transaction_time ? (
          <span>{dayjs(record.transaction_time).format('YYYY-MM-DD HH:mm:ss')}</span>
        ) : (
          ''
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      fixed: 'right',
      //width: 200,
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (_text, record) => (
        <Space>
          <PermissionButton permission="view">
            <Button type="link" onClick={() => handleView(record)}>
              查看
            </Button>
          </PermissionButton>
        </Space>
      ),
    },
  ];

  // 转换 value 到 label
  const formatSubmitValue = (val, arr) => {
    let textArr;
    let text;
    textArr = _.isArray(val) ? val : val.split(',');
    text = textArr.map(v => utils.findLabelDeep(arr, String(v))).join('-');
    return text;
  };

  const handleView = record => {
    const transaction_type_text = record.transaction_type
      ? formatSubmitValue(record.transaction_type, STU_CHANGE_TYPE)
      : '';
    const obj = { ...record, transaction_type: transaction_type_text };
    console.log('🚀 ~ handleView ~ obj:', obj);
    setCur(obj);
    setVisible(true);
  };

  React.useEffect(() => {
    searchFunc({}, 1, pageSize);
  }, []);

  const pageChange = (pageIndex, pageSize) => {
    searchFunc(curFormPanelObject?.getFieldsValue(), pageSize, pageIndex);
    setPageIndex(pageIndex);
    setPageSize(pageSize);
  };
  return (
    <PageContainer header={<Breadcrumb items={[{ title: '异动管理' }]} />}>
      <FormPanel
        btnsAlign={FormPanelBtnAlign.right}
        restBtnText="重置"
        submitBtnText="查询"
        onLoad={(formPanelObject: FormPanelObject) => {
          setCurFormPanelObject(formPanelObject);
        }}
        onFinish={(formPanelObject: FormPanelObject) => {
          searchFunc({ ...formPanelObject.getFieldsValue() }, 1, pageSize);
        }}
        template={list}
      />
      <Table
        dataSource={value}
        columns={columns}
        loading={loading}
        scroll={{ x: 'max-content' }}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
      <Modal width="80%" title="详情" footer={null} open={visible} onCancel={() => setVisible(false)}>
        <FormPanel
          formStatus={FormPanelStatus.nonEdit}
          buttonsDisplay={FormPanelBtnDisplay.none}
          values={cur}
          template={showlist}
        />
      </Modal>
    </PageContainer>
  );
};

export default Groups;
